<template>
  <div class="file-upload-demo">
    <h1>大文件分片上传/断点续传/文件秒传_上传示例</h1>

    <AdvancedUpload
      title="文件上传"
      accept=".jpg,.jpeg,.png,.pdf,.doc,.docx,.xls,.xlsx,.zip,.rar"
      :maxFileSize="1024 * 1024 * 1024 * 2"
      :chunkSize="2 * 1024 * 1024"
      @upload-success="handleUploadSuccess"
      @upload-error="handleUploadError"
      @upload-progress="handleUploadProgress"
    />

    <div v-if="uploadedFiles.length > 0" class="uploaded-files">
      <h2>已上传文件</h2>
      <el-table :data="uploadedFiles" style="width: 100%">
        <el-table-column prop="fileName" label="文件名" />
        <el-table-column prop="fileSize" label="文件大小">
          <template #default="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" link @click="previewFile(scope.row.url)">预览</el-button>
            <el-button type="success" link @click="downloadFile(scope.row.url, scope.row.fileName)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import AdvancedUpload from '@/components/AdvancedUpload.vue'

const uploadedFiles = ref([])

// 处理上传成功
const handleUploadSuccess = (fileInfo) => {
  uploadedFiles.value.push({
    fileName: fileInfo.fileName,
    fileSize: fileInfo.fileSize,
    url: fileInfo.url,
    md5: fileInfo.fileMd5
  })
}

// 处理上传错误
const handleUploadError = (error) => {
  console.error('上传失败', error)
}

// 处理上传进度
const handleUploadProgress = (progressInfo) => {
  console.log('上传进度', progressInfo.progress)
}

// 预览文件
const previewFile = (url) => {
  window.open(url, '_blank')
}

// 下载文件
const downloadFile = (url, fileName) => {
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'

  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>

<style scoped>
.file-upload-demo {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  margin-bottom: 20px;
}

.uploaded-files {
  margin-top: 30px;
}

h2 {
  margin-bottom: 15px;
}
</style>
